#include "packet.h"
#include <QDebug>

Packet::Packet(QByteArray byteArr)
{
    fromByteArray(byteArr);
}

Packet::Packet()
{
    protocol_id = 0;
    sequence = 0;
    ack = 0;
    ack_bitfield = QBitArray(32);
    data = "";
}

void Packet::setProtocolId(const quint32& id)
{
    protocol_id = id;
}
void Packet::setSequence(const quint32& s)
{
    sequence = s;
}
void Packet::setAck(const quint32& a)
{
    ack = a;
}
void Packet::setAckBitfield(const QBitArray& bf)
{
    ack_bitfield = bf;
}

void Packet::setData(PacketData* d)
{
    data = d->getData();
    //delete d;
}

void Packet::setSenderAddress(const QHostAddress& addr)
{
    senderAddress = addr;
}

void Packet::setSenderPort(const quint16& p)
{
    senderPort = p;
}

void Packet::setIsReliable(const bool& is)
{
    isReliable = is;
}

void Packet::setSendTime(const quint32& st)
{
    sendTime = st;
}

quint32 Packet::getProtocolId()
{
    return protocol_id;
}

quint32 Packet::getSequence()
{
    return sequence;
}

quint32 Packet::getAck()
{
    return ack;
}

QBitArray Packet::getAckBitfield()
{
    return ack_bitfield;
}

QByteArray Packet::getData()
{
    return data;
}

QString Packet::getStringData()
{
    return data.data();
}

bool Packet::getIsReliable()
{
    return isReliable;
}

quint32 Packet::getSendTime()
{
    return sendTime;
}

QHostAddress Packet::getSenderAddress()
{
    return senderAddress;
}

quint16 Packet::getSenderPort()
{
    return senderPort;
}

QString Packet::getHostPortKey()
{
    return senderAddress.toString() + ":" + QString::number(senderPort);
}

void Packet::fromByteArray(QByteArray arr)
{
    QDataStream d(&arr, QIODevice::ReadOnly);
    d >> protocol_id;
    d >> sequence;
    d >> ack;
    d >> ack_bitfield;
    d >> data;
    d.unsetDevice();
}

QByteArray Packet::toByteArray()
{
    QByteArray arr;
    QDataStream str(&arr, QIODevice::WriteOnly);
    str << protocol_id;
    str << sequence;
    str << ack;
    str << ack_bitfield;
    str << data;
    str.unsetDevice();
    return arr;
}


